package com.api.util.repo.impl;

import com.api.test.Api;
import com.api.util.repo.DtoFactory;
import com.api.util.repo.DtoRepository;
import com.zyncro.api.IOrganizationApiService;

public class DomainUserDtoFactory implements DtoFactory<DomainUser> {

	private static final long STORAGE_1MB = 1048576;

	private final Api api;

	private final DomainUser mainAdmin;

	private final FactoryParams params = new FactoryParams();

	public DomainUserDtoFactory(Api api, DomainUser mainAdmin, FactoryParams factoryParams) {
		this.api = api;
		this.mainAdmin = mainAdmin;

		params.set("name", "user");
		params.set("lastname", "%s");
		params.set("email", "%s@yopmail.com");
		params.set("password", "123456");
		params.set("storage", STORAGE_1MB);
		params.set("canPublishCorporateFeed", false);
		params.set("canCreateGroups", false);
		params.set("canCreateDepartments", false);
		params.set("isAdministrator", false);
		params.set("langString", null);
		params.set("attributes", null);

		params.updateFields(factoryParams);
	}

	public DomainUserDtoFactory(Api api, DomainUser mainAdmin) {
		this(api, mainAdmin, new FactoryParams());
	}

	@Override
	public DomainUser createDto(String property, DtoRepository repository) {
		DomainUser user = new DomainUser();
		try {
			String name = params.get("name");
			String lastname = params.get("lastname");
			String email = params.get("email");
			String password = params.get("password");
			long storage = params.get("storage");
			boolean canPublishCorporateFeed = params.get("canPublishCorporateFeed");
			boolean canCreateGroups = params.get("canCreateGroups");
			boolean canCreateDepartments = params.get("canCreateDepartments");
			boolean isAdministrator = params.get("isAdministrator");
			String langString = params.get("langString");
			String attributes = params.get("attributes");

			lastname = String.format(lastname, property);
			email = String.format(email, property);

			api.login(mainAdmin.getAppId(), mainAdmin.getPassword());

			String result = api.getService(IOrganizationApiService.class).addUser(name, lastname, email, password, storage,
					canPublishCorporateFeed, canCreateGroups, canCreateDepartments, isAdministrator, langString, attributes);

			user.setAppId(result);
			user.setEmail(email);
			user.setName(name);
			user.setLastName(lastname);
			user.setPassword(password);
			user.setQuota(storage);

		} catch (Exception e) {
			throw new IllegalStateException(String.format("Couldn't create domainUser for property '%s'", property), e);
		}

		return user;
	}
}
